package actions;

import java.awt.event.ActionEvent;
import java.util.StringTokenizer;

import streaming.Call;
import client.ClientApplication;
import client.ClientBindObject;
import client_gui.ClientWindow;
import client_tree.User;

public class StopCallAction extends RLMAbstractAction {

	
	public StopCallAction(ClientWindow owner) {
		setActionOwner(owner);
		putValue(SMALL_ICON, loadIcon("images/stop_call.png"));
		putValue(NAME, "Stop Call");
		putValue(SHORT_DESCRIPTION, "Stop call");
		putValue(ACTION_COMMAND_KEY, "stop_call_action");
	}
	
	private ActionEvent event;
	private User user;
	private ClientBindObject cbo;
	private Call call;
	
	private boolean invoked = false;
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		if ( invoked ) {
			return;
		}
		else {
			invoked = true;
		}

		event = e;
		
		String actionCommand = event.getActionCommand();
		
		if ( actionCommand.equals("stop_call_action") ) {
			return;
		}
		
		StringTokenizer tokens = new StringTokenizer(actionCommand);
		
		user = getActionOwner().getApplicaton().getClientModel().getOnlineModel().getUserByUsername(tokens.nextToken());
		
		if ( user == null ) {
			return;
		}
		
		cbo = ClientApplication.clientBinding.get(user.getUsername());
		
		if ( cbo == null || cbo.getConnection() == null ) {
			return;
		}
		
		String cmd = tokens.nextToken();
		
		call = cbo.getCall();
		
		if ( call == null ) {
			return;
		}
		
		if ( cbo.getDialog() != null && cbo.getDialog().getStreamingPanel() != null ) {		
			cbo.getDialog().getStreamingPanel().showNoVideoPanel();
			cbo.getDialog().getStreamingPanel().showMonitorNoVideoPanel();
			cbo.getDialog().getStreamingPanel().refreshVideo();
		}
		
		if ( call.isAudioRequested() || call.isVideoRequested() || call.isAudioEstablished() || call.isVideoEstablished() ) {
			// slanje komande
			// C - conversation
			// W - waiting
	//		cbo.getConnection().writeData("STOP_CALL " + getActionOwner().getApplicaton().getClientUser().getUsername() + " " + actionCommand);
	//		cbo.getConnection().buffers[CALL_REQUEST].write("CALL_RESPONSE N" + CRLF);
			
			cbo.getConnection().setMessage(CALL_REQUEST, "STOP_CALL " + getActionOwner().getApplicaton().getClientUser().getUsername() + " " + cmd);
		}
		
		call.hangUpCall();
		cbo.setCall(null);
		
		invoked = false;
	}
	
}
